package cn.feuler.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class RegisterFilter implements GlobalFilter, Ordered {

    public static final Map<String, AtomicInteger> registerCount = new ConcurrentHashMap<>();
    public static final Integer PEER_IP_MAX_REGISTER = 100;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        if (!path.startsWith("/api/user/register")) {
            return chain.filter(exchange);
        }

        String hostAddress = request.getRemoteAddress().getAddress().getHostAddress();
        AtomicInteger count = registerCount.getOrDefault(hostAddress, new AtomicInteger());
        count.getAndAdd(1);
        registerCount.putIfAbsent(hostAddress, count);
        if (count.get() > PEER_IP_MAX_REGISTER) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.SEE_OTHER);
            String data = "频繁注册，请求已拒绝";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
